//
//  HWCommonWebViewController.m
//  嗨文
//
//  Created by 响当当 on 5/9/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "HWCommonWebViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "TGWebProgressLayer.h"
#import <DWKWebView.h>
#import "JsApiTest.h"
#import "HWCommonTest.h"

@interface HWCommonWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic,strong)DWKWebView *webView;
@property (nonatomic, strong)TGWebProgressLayer *webProgressLayer;  //加载进度条
@property (nonatomic, strong)NSMutableURLRequest *request;
@end

@implementation HWCommonWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setDefaultNavWithTitle:self.titleStr];
    
    [self configSubView];
    [self buryPoint];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeProgress];
}

#pragma 判断是返回首页还是返回
- (void)backAction
{
    if ([self.webView canGoBack])
    {
        [self.webView goBack];
    }else
    {
        
        if ([self.type isEqualToString:@"1"])
        {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
        else
        {
            [self.navigationController popViewControllerAnimated:false];
        }
    }
}
#pragma 返回app
- (void)goHome
{
    [self.navigationController popViewControllerAnimated:false];

}

#pragma 配置子视图
- (void)configSubView
{
    self.webView = [self getCookieWebview];
    [self.view addSubview:self.webView];
}

//  注意，CookieWebview 和 正常的 webview 是不同的
- (DWKWebView *)getCookieWebview
{
    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    webConfig.userContentController = [[WKUserContentController alloc] init];
    webConfig.allowsInlineMediaPlayback = YES;
    // 设置偏好设置
    webConfig.preferences = [[WKPreferences alloc] init];
    // 默认为0
    webConfig.preferences.minimumFontSize = 10;
    // 默认认为YES
    webConfig.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    
    // web内容处理池
    webConfig.processPool = [[WKProcessPool alloc] init];
    // 将所有cookie以document.cookie = 'key=value';形式进行拼接
    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'access_token=%@'; document.cookie = 'device=%@';",current_User.token,@"ios"];
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookieValue
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    [userContentController addUserScript:cookieScript];
    
    webConfig.userContentController = userContentController;
    
    _webView = [[DWKWebView alloc]initWithFrame:CGRectMake(0,NAVIBAR_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT-TABBAR_HEIGHT-10*kUIScaleBasePlus) configuration:webConfig];
    _webView.navigationDelegate = self;
    
    self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    
    [_webView loadRequest:self.request];
    
    [_webView addJavascriptObject:[[HWCommonTest alloc]init] namespace:nil];
    
    
    return _webView;
}

- (NSMutableString*)getCookieValue{
    // 在此处获取返回的cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }
    // cookie重复，先放到字典进行去重，再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
        [cookieValue appendString:appendString];
    }
    return cookieValue;
}

//配置进度条
- (TGWebProgressLayer  *)webProgressLayer
{
    if (!_webProgressLayer)
    {
        _webProgressLayer = [[TGWebProgressLayer alloc] init];
        _webProgressLayer.frame = CGRectMake(0, kNavgationBarHeight - 2, WIDTH, 2);
        _webProgressLayer.strokeColor = kBtnOrange.CGColor;
        [self.navigationController.navigationBar.layer addSublayer:_webProgressLayer];
    }
    return _webProgressLayer;
}

- (void)removeProgress
{
    if (_webProgressLayer)
    {
        [_webProgressLayer tg_closeTimer];
        [_webProgressLayer removeFromSuperlayer];
        _webProgressLayer = nil;
    }
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self.webProgressLayer tg_WebViewPathChanged:webView.estimatedProgress];
}

// 1. 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *scheme = [url scheme];
    if ([scheme isEqualToString:@"tel"] || [scheme isEqualToString:@"weixin"])
    {
        [[UIApplication sharedApplication] openURL:url];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 4, 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}
// 8页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [_webProgressLayer tg_finishedLoadWithError:error];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [_webProgressLayer tg_finishedLoadWithError:nil];
}


- (void)dealloc
{
    [self removeProgress];
}

- (void)buryPoint
{
    NSString *lastStayTime = [kUserDefaults objectForKey:@"time"];
    NSString *nowStayTime = [NSString stringWithFormat:@"%ld",[[HWUtilties getNowTimeTimestamp3] integerValue] - lastStayTime.integerValue];
    
    [HWUtilties buryPointWithStayTime:nowStayTime
                            timestamp:[HWUtilties getNowTimeTimestamp3]
                             memberId:current_User.userID
                              fromUrl:nil
                                toUrl:self.toUrl
                               fromId:nil
                                 toId:self.toId];
}

@end
